import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:chatbot/manager/event_bus.dart';
import 'package:chatbot/manager/store_manager.dart';
import 'package:chatbot/model/completion_model.dart';
import 'package:chatbot/model/creator_list_model.dart';
import 'package:chatbot/model/event.dart';
import 'package:chatbot/model/role_list_model.dart';
import 'package:chatbot/model/role_model.dart';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/cupertino.dart';

class DioManager {
  factory DioManager() => _getInstance();

  static DioManager get instance => _getInstance();
  static DioManager? _instance;
  late Dio dio;

  DioManager._internal() {
    dio = Dio();

    dio.options.baseUrl = "https://www.haowangpt.cn:9443/";
    // dio.options.baseUrl = "https://localhost:9443/";
    dio.options.connectTimeout = const Duration(seconds: 120); //120s
    dio.options.receiveTimeout = const Duration(seconds: 120); //120s
    dio.options.contentType = Headers.formUrlEncodedContentType;

    dio.httpClientAdapter = IOHttpClientAdapter(
      createHttpClient: () {
        final client = HttpClient();
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) {
          return true;
        };
        return client;
      },
    );

    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          // 如果你想完成请求并返回一些自定义数据，你可以使用 `handler.resolve(response)`。
          // 如果你想终止请求并触发一个错误，你可以使用 `handler.reject(error)`。
          if (options.method == "GET") {
            options.responseType = ResponseType.stream;
          } else {
            options.responseType = ResponseType.json;
          }
          String key = getRandom();
          String timeInterval = "${DateTime.now().millisecondsSinceEpoch}";
          options.queryParameters = {
            'version': StoreManager.getVersion(),
            'bid': StoreManager.getBid(),
            'uuid': StoreManager.getUUID(),
            'uid': StoreManager.getUID(),
            'vip': StoreManager.isVip(),
            'sign_key': key,
            'timeInterval': timeInterval,
            // timeInterval+ 正式服加上
            'sign': sha256.convert(utf8.encode(StoreManager.getVersion() +
                StoreManager.getBid() +
                timeInterval +
                '5b3a5158289a85d03da1d13163e0060d' +
                key))
          };
          return handler.next(options);
        },
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          // 如果你想终止请求并触发一个错误，你可以使用 `handler.reject(error)`。
          return handler.next(response);
        },
        onError: (DioException e, ErrorInterceptorHandler handler) {
          // 如果你想完成请求并返回一些自定义数据，你可以使用 `handler.resolve(response)`。
          return handler.next(e);
        },
      ),
    );
  }

  static getRandom() {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    int length = 30;

    String left = '';
    for (var i = 0; i < length; i++) {
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  static DioManager _getInstance() {
    _instance ??= DioManager._internal();
    return _instance!;
  }

  getAllRoles(int currentPage) async {
    try {
      Response response = await DioManager.instance.dio.post(
        "personal_helper/listV3",
        data: {"page":currentPage},
      );
      Map result = response.data;
      // debugPrint('getAllRoles response：${response.data.toString()}');
      bool isSuccess = _isResponseSuccess(result);
      if (isSuccess) {
        RoleListModel roleListModel =
        RoleListModel.fromMap(result as Map<String, dynamic>);

        // if (roleListModel.data.isNotEmpty) {
        //   debugPrint("size=${roleListModel.data.length}");
        // }
        // await StoreManager.putRoleJson(json.encode(result));
        // EventManager.instance.eventBus.fire(RoleListSuccess());
        return roleListModel;
      } else {
        // EventManager.instance.eventBus.fire(RoleListSuccess());
        return null;
      }
    } catch (e) {
      // EventManager.instance.eventBus.fire(RoleListSuccess());
      debugPrint('getAllRoles errors:' + e.toString());
      return null;
    }
  }

  getAllCreators(int currentPage) async {
    try {
      Response response = await DioManager.instance.dio.post(
        "creator/listV3",
        data: {"page":currentPage},
      );
      Map result = response.data;
      // debugPrint('getAllCreators response：${response.data.toString()}');
      bool isSuccess = _isResponseSuccess(result);
      if (isSuccess) {
        CreatorListModel creatorListModel =
        CreatorListModel.fromMap(result as Map<String, dynamic>);
        //
        // if (creatorEntity.data.isNotEmpty) {
        //   debugPrint("size=${creatorEntity.data.length}");
        // }
        // await StoreManager.putCreatorJson(json.encode(result));
        // EventManager.instance.eventBus.fire(CreatorListSuccess());
        return creatorListModel;
      } else {
        // EventManager.instance.eventBus.fire(CreatorListSuccess());
        return null;
      }
    } catch (e) {
      // EventManager.instance.eventBus.fire(CreatorListSuccess());
      return null;
    }
  }

  void registerUid() async {
    Response response = await DioManager.instance.dio.post(
      "uid/add",
      data: {},
    );
  }

  _isResponseSuccess(Map response) {
    return response.containsKey('code') && response['code'] == 200;
  }
}
